import React, { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { connect } from 'react-redux'
import { setRole, setMediaStatus } from '@/store/actions'
import { useEffectOnce } from '@/utils/hooks'
import { postRoom, putUserInfo } from '@/api/index'
import { qs, sq, showBgAnimation } from '@/utils/index'

import { Button } from 'antd'
import Header from './components/Header'
import SetAvatarEl from './components/SetAvatarEl'
import SetNameEl from './components/SetNameEl'
import SetRoomIdEl from './components/SetRoomIdEl'
import SetMediaEl from './components/SetMediaEl'

import './index.scss'

const JoinRoom = ({
  userId,
  setRoleAction,
  setMediaStatusAction
}) => {
  const navigate = useNavigate()

  /* 触发action, 修改当前role */
  const role = useParams().role

  const [nickname, setNickname] = useState(sq().nickname || '')
  const [avatar, setAvatar] = useState('')
  const [roomId, setRoomId] = useState(sq().roomId || '')
  const [openAudio, setOpenAudio] = useState(true)
  const [openCamera, setOpenCamera] = useState(true)

  const createRoom = async() => {
    try {
      const res = await postRoom(userId)

      navigate(`/room/${ res.data.id }${ qs({
        nickname,
      }) }`)
    } catch (err) {
      console.log(err)
    }
  }
  const onclickJoin = async() => {
    await putUserInfo({
      userId,
      nickname,
      avatar
    })
    setMediaStatusAction({
      openAudio,
      openCamera
    })
    setRoleAction(role)

    if (role === 'Host') {
      createRoom()
    } else {
      navigate(`/room/${ roomId }${ qs({
        nickname,
      }) }`)
    }
  }

  useEffectOnce(() => {
    showBgAnimation('Join-Room-Animation')
  }, [])

  return (
    <div className="join-room">
      <div
        className="animation"
        id="Join-Room-Animation"
      />
      <Header role={role} />
      <SetAvatarEl
        avatar={avatar}
        setAvatar={setAvatar} />
      <SetNameEl
        nickname={nickname}
        setNickname={setNickname} />

      {
        role === 'Audience' && (
          <SetRoomIdEl
            roomId={roomId}
            setNickname={setRoomId} />
        )
      }
      {/* 选择打开或者关闭摄像头与声音 */}
      <SetMediaEl
        openAudio={openAudio}
        openCamera={openCamera}
        setOpenAudio={setOpenAudio}
        setOpenCamera={setOpenCamera} />
      <Button
        className="join-btn"
        onClick={onclickJoin}
        shape="round"
        size="large"
        type="primary">
        {role === 'Host' ? '创建观影厅' : '加入观影厅'}
      </Button>
    </div>
  )
}

const mapStateToProps = (state) => {
  return {
    ...state
  }
}
const mapActionsToProps = (dispatch) => {
  return {
    setRoleAction: (role) => dispatch(setRole(role)),
    setMediaStatusAction: (role) => dispatch(setMediaStatus(role)),
  }
}

export default connect(mapStateToProps, mapActionsToProps)(JoinRoom)
